package com.lkm.app_ui.ui.fj.img;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;

import androidx.annotation.Nullable;

import com.lkm.app_ui.AppConfig;
import com.lkm.app_ui.AppConst;
import com.lkm.app_ui.ui.fj.FjOrder;
import com.lkm.frame.file.FileHelper;
import com.lkm.frame.otto.LinkBus;

import java.io.File;
import java.io.FileOutputStream;



class ImgFiler {

    public static void ayncDeleteAllTemp() {
        AppConst.getTaskExecutor().execute(new Runnable() {
            @Override
            public void run() {
                deleteAllTemp();
            }
        });
    }



    public static void ayncSave(FjOrder.FjItem goodEntity, byte[] data) {

        AppConst.getTaskExecutor().execute(new Runnable() {
            @Override
            public void run() {
                save_(goodEntity, data);
            }
        });
    }


    public synchronized static @Nullable File[] getUpFiles() {
        return new File(AppConfig.DataFile.fjImgUpFileDir).listFiles();
    }



    private synchronized static void deleteAllTemp() {
        FileHelper.deleteFolder(new File(AppConfig.DataFile.fjImgUpFileDir));
    }

    private synchronized static void save_(FjOrder.FjItem goodEntity, byte[] data) {
        Bitmap bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);
        int width = bitmap.getWidth();
        int height = bitmap.getHeight();
        int cx = width/2;
        int cy = height/2;
        int offsex = cx / 3;
        int offsey = cy / 3;
        int offsex1 = offsex;
        int offsey1 = offsey;
        offsex = offsex/2;

        
        Matrix matrix = new Matrix();
        matrix.setRotate(180,width/2,width/2);

        Bitmap bitmap1 = Bitmap.createBitmap(bitmap,offsex,offsey,width - (offsex+offsex1),height - (offsey+offsey1) ,matrix,false);
        bitmap.recycle();
        bitmap = bitmap1;

        
        String xxsavePath = AppConfig.DataFile.toFjImgUpFilePath(goodEntity);
        try {
            File ff = new File(xxsavePath);
            File ffp = ff.getParentFile();
            if (!ffp.exists()) {
                ffp.mkdirs();
            }
            bitmap.compress(Bitmap.CompressFormat.JPEG, 90, new FileOutputStream(ff));

            LinkBus.sendBroadcast(new OnFjImageTackEvent(xxsavePath,goodEntity));

            
            UpImageTask.tryUp();
        } catch (Exception e) {
        }
    }

}
